package com.typhoon.spring_jdbctemplate.dao.support;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class CustomJdbcTemplate extends JdbcTemplate implements CustomJdbcOperations {
	
	public CustomJdbcTemplate() {
	}

	/**
	 * Construct a new JdbcTemplate, given a DataSource to obtain connections from.
	 * <p>Note: This will not trigger initialization of the exception translator.
	 * @param dataSource the JDBC DataSource to obtain connections from
	 */
	public CustomJdbcTemplate(DataSource dataSource) {
		super(dataSource);
	}
	
	public CustomJdbcTemplate(DataSource dataSource, boolean lazyInit) {
		super(dataSource, lazyInit);
	}

	@Override
	public <T> PageResult<T> page(String sql, RowMapper<T> rowMapper, PageQuery pageQuery, Object... args)
			throws DataAccessException {
		PageInfo page = new PageInfo();
		int pageSize = pageQuery.getPageSize();
		if(pageSize >= 5000) {
			logger.warn("CustomJdbcTemplate#page pageSize has overhead 5000;pageSize:"+pageSize);
		}
		int offset = (pageQuery.getPageIndex() - 1) * pageSize;
		StringBuffer countSql = new StringBuffer();
        countSql.append(MySql5PageHepler.getCountString(sql));
        int totalRows = this.queryForObject(countSql.toString(), args, Integer.class);
        page.init(totalRows, pageSize, pageQuery.getPageIndex());
        if(totalRows <= 0) {//查询总数没有数据，就没有必要再去查询具体数据
        	return PageResult.wrap(page, null);
        }
        String pageSql = MySql5Dialect.getLimitString(sql, offset, pageSize);
        List<T> list = this.query(pageSql, rowMapper, args);
		return PageResult.wrap(page, list);
	}

}
